﻿using System.Collections.Generic;
using System.Windows.Input;
using Bulb.Core.Services.CollectionService;
using Bulb.Core.Services.CollectionService.Messages;
using Bulb.Core.Services.DataStore;
using Cirrious.MvvmCross.Plugins.JsonLocalisation;
using Cirrious.MvvmCross.Plugins.Messenger;
using Cirrious.MvvmCross.ViewModels;

namespace Bulb.Core.ViewModels
{
    public class HomeViewModel : BaseViewModel
    {
        private MvxSubscriptionToken _collectionChangedSubscriptionToken;
        private MvxSubscriptionToken _languageChangedSubscriptionToken;

        public SettingsViewModel SettingsViewModel { get; set; }

        private List<BulbItem> _items;
        public List<BulbItem> Items
        {
            get { return _items; }
            set
            {
                _items = value;
                RaisePropertyChanged(() => Items);
            }
        }

        public HomeViewModel(ICollectionService collectionService, IMvxMessenger messenger, IMvxTextProviderBuilder builder) 
            : base(collectionService)
        {
            Items = (List<BulbItem>)CollectionService.All();
            _collectionChangedSubscriptionToken = messenger.Subscribe<CollectionChangedMessage>(OnCollectionChanged);
            _languageChangedSubscriptionToken = messenger.Subscribe<LanguageChangedMessage>(OnLanguageChanged);
            SettingsViewModel = new SettingsViewModel(collectionService, builder, messenger);
        }

        private void OnCollectionChanged(CollectionChangedMessage obj)
        {
            Items = (List<BulbItem>)CollectionService.All();
        }

        private void OnLanguageChanged(LanguageChangedMessage obj)
        {
            RaisePropertyChanged(() => TextSource);
        }

        public ICommand ShowDetailCommand
        {
            get
            {
                return new MvxCommand<BulbItem>(item =>
                {
                    if (item != null)
                    {
                        ShowViewModel<DetailBulbViewModel>(new DetailBulbViewModel.Nav {Id = item.Id});
                    }
                });
            }
        }

        public ICommand OnCommand
        {
            get { return new MvxCommand<BulbItem>(item => CollectionService.On(item)); }
        }

        public ICommand OffCommand
        {
            get { return new MvxCommand<BulbItem>(item => CollectionService.Off(item)); }
        }

        public ICommand DeleteCommand
        {
            get { return new MvxCommand<BulbItem>(item => CollectionService.Delete(item)); }
        }

        public ICommand SettingsCommand
        {
            get { return new MvxCommand(() => ShowViewModel<SettingsViewModel>()); }
        }
    }
}
